<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Upload_Controllers_File extends Gio_Core_Controller 
{
	/**
	 * Watermark font 
	 * @const string
	 */
	const WATERMARK_FONT  = 'watermark.ttf';
	
	/* ========== Backend actions =========================================== */
	
	public function uploadAction()
	{
		$this->disableLayout();
		$this->setNoRender();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			exit;
		}
		
		/**
		 * Authentication
		 */
		$phpSessionId = $request->getPost('PHPSESSID');
		$session 	  = Gio_Core_Session::getSessionById($phpSessionId);	
		$json = new Services_JSON();
		$user = (null == $session || null == $session['data']) 
										? null : $json->decode($session['data']);
										
		if (null == $user) {
			return;
		}
		
		/**
		 * Get config
		 */
		$configFile = MOD_DIR . DS . 'upload' . DS . 'configs' . DS . 'config.ini';
		$iniArray = @parse_ini_file($configFile, true);
		$tool 	= isset($iniArray['thumbnail']['tool']) ? $iniArray['thumbnail']['tool'] : 'gd';
		$sizes 	= array();
		foreach ($iniArray['size'] as $key => $value) {
			list($method, $width, $height) = explode('_', $value);
			$sizes[$key] = array('method' => $method, 'width' => $width, 'height' => $height);
		}
		
		$user = (array)$user;
		$userName = $user['username'];
		$module   = $request->getPost('mod');
		$thumbnailSizes = $request->getPost('thumbnails', null);
		
		/**
		 * Prepare folders
		 */
		$dir  = ROOT_DIR . DS . 'upload';
		$path = implode(DS, array($module, $userName, date('Y'), date('m')));
		Gio_Core_File::createDirs($dir, $path);
		
		/**
		 * Upload file
		 */
		$ext 	   = explode('.', $_FILES['Filedata']['name']);
		$extension = $ext[count($ext) - 1];
		unset($ext[count($ext) - 1]);
		$fileName  = date('YmdHis_') . implode('', $ext);
		$file 	   = $dir . DS . $path . DS . $fileName . '.' . $extension;
		move_uploaded_file($_FILES['Filedata']['tmp_name'], $file);
		
		/**
		 * Water mark
		 * @since 2.0.4
		 */
		$watermark   = $request->getParam('watermark');
		$overlayText = $color = $overlayImage = $position = $sizesApplied = null;

		if ((boolean)$watermark) {
			$overlayText  = $request->getParam('text');
			$color 		  = $request->getParam('color');
			$overlayImage = $request->getParam('image');
			$position 	  = $request->getParam('position');
			$sizesApplied = $request->getParam('sizes');		
			$sizesApplied = explode(',', $sizesApplied);
		}
		
		/**
		 * Generate thumbnails if requested
		 */
		if (!isset($thumbnailSizes) || $thumbnailSizes == null) {
			$thumbnailSizes = array_keys($sizes);
		} else if ($thumbnailSizes != 'none') {
			$thumbnailSizes = explode(',', $thumbnailSizes);
		}
		$service = null;
		switch (strtolower($tool)) {
			case 'imagemagick':
				$service = new Gio_Image_ImageMagick();
				break;
			case 'gd':
				$service = new Gio_Image_GD();
				break;
		}
		
		$ret = array();
		
		/**
		 * Remove script filename from base URL
		 */
		$baseUrl = $request->getBaseUrl();
		$prefixUrl 		 = rtrim($baseUrl, '/') . '/upload/' . $module . '/' . $userName . '/' . date('Y') . '/' . date('m');
		$ret['original'] = array(
			'url'  => $prefixUrl . '/' . $fileName . '.' . $extension,
			'size' => null,
		);
		
		if ($thumbnailSizes != 'none') {
			$service->setFile($file);
			$ret['original']['size'] = $service->getWidth() . ' x ' . $service->getHeight();
			
			foreach ($thumbnailSizes as $s) {
				$service->setFile($file);
				$method = $sizes[$s]['method'];
				$width 	= $sizes[$s]['width'];
				$height = $sizes[$s]['height'];
				
				$f 		 = $fileName . '_' . $s . '.' . $extension;
				$newFile = $dir . DS . $path . DS . $f;
				
				/**
				 * Create thumbnail
				 */
				switch ($method) {
					case 'resize':
						$service->resizeLimit($newFile, $width, $height);						
						break;
					case 'crop':
						$service->crop($newFile, $width, $height);						
						break;
				}
				
				/**
				 * Create watermark if requested
				 */
				if ((boolean)$watermark) {
					$service->setWatermarkFont(ROOT_DIR . DS . 'data' . DS . 'upload' . DS . self::WATERMARK_FONT);
					$service->setFile($newFile);
					
					if ($overlayText && in_array($s, $sizesApplied)) {
						$service->watermarkText($overlayText, $position, array('color' => $color, 'rotation' => 0, 'opacity' => 50, 'size' => null));
					}
					if ($overlayImage && in_array($s, $sizesApplied)) {
						$overlay = explode('/', $overlayImage);
						$n 		 = count($overlay);	
						$overlay = implode(DS, array($dir, 'multimedia', $overlay[$n - 4], $overlay[$n - 3], $overlay[$n - 2], $overlay[$n - 1]));
						$service->watermarkImage($overlay, $position);
					}
				}
				
				$ret[$s] = array(
					'url'  => $prefixUrl . '/' . $f,
					'size' => $width . ' x ' . $height,
				);
			}
		}
		
		/**
		 * Return the reponse
		 */
		$json = new Services_JSON();
		$this->getResponse()->setBody($json->encodeUnsafe($ret));
	}
}
